# #!/usr/bin/env python
# # -*- coding: utf-8 -*-
#
from flask import jsonify, request
from flask_restful import Resource
from Utility.api_security import APISecurity
from Utility.error_code import error_code
import tools
from Settings.config import Config
import odoorpc
import logging

FORMAT = "%(asctime)s %(thread)d %(message)s"
logging.basicConfig(level=logging.INFO, format=FORMAT)


# class {{ camel_name }}API(Resource):
class API(Resource):
    def post(self):
        """
        {{ modelName.name }}新增
        :request: post
        :param: data dict
        :returns: json string
        """
        try:
            # token校验
            payload = APISecurity().verify_access_token()
            if not payload:
                return jsonify({'code': 901, 'msg': error_code[901]})

            odoo = odoorpc.ODOO(Config.ODOO_HOST, port=Config.ODOO_PORT)
            odoo.login(Config.ODOO_DB, payload['login'], payload['pwd'])
            record = tools.dict_to_snake(request.json['data'])
            record_id = odoo.env['{{ modelName }}'].create(record)
            return jsonify({'code': 0, 'msg': 'success', 'data': record_id})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 502, 'msg': error_code[502]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})
        finally:
            odoo.logout()

    def put(self):
        """
        {{ modelName.name }}修改，根据条件查询出符合条件的数据集再修改
        :request: put
        :param: params dict 查询条件
        :param: data dict 更新数据
        :returns: json string
        """
        try:
            # token校验
            payload = APISecurity().verify_access_token()
            if not payload:
                return jsonify({'code': 901, 'msg': error_code[901]})

            odoo = odoorpc.ODOO(Config.ODOO_HOST, port=Config.ODOO_PORT)
            odoo.login(Config.ODOO_DB, payload['login'], payload['pwd'])
            domain = tools.dict_to_domain(request.json['params'])
            ids = odoo.env['{{ modelName }}'].search(domain)
            if ids:
                data = tools.dict_to_snake(request.json['data'])
                odoo.env['{{ modelName }}'].write(ids, data)
            return jsonify({'code': 0, 'msg': 'success', 'data': ids})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 502, 'msg': error_code[502]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})
        finally:
            odoo.logout()

    def get(self):
        """
        {{ modelName.name }}查询，返回一条字典记录
        :request: get
        :param: params dict 字典类型查询条件，目前只支持多个条件的“与”关系，不支持“或”、“非”关系
        :returns: json string
        """
        try:
            # token校验
            payload = APISecurity().verify_access_token()
            if not payload:
                return jsonify({'code': 901, 'msg': error_code[901]})

            odoo = odoorpc.ODOO(Config.ODOO_HOST, port=Config.ODOO_PORT)
            odoo.login(Config.ODOO_DB, payload['login'], payload['pwd'])
            domain = tools.dict_to_domain(request.json['params'])
            fields = odoo.env['{{ modelName }}'].get_fields_all()
            data_list = odoo.env['{{ modelName }}'].search_read(domain, fields, limit=1)
            if data_list:
                data = tools.dict_to_camel(data_list[0])
            else:
                data = {}
            return jsonify({'code': 0, 'msg': 'success', 'data': data})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 502, 'msg': error_code[502]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})
        finally:
            odoo.logout()


# class {{ camel_name }}ListAPI(Resource):
class ListAPI(Resource):
    def get(self):
        """
        {{ modelName.name }}列表查询，返回列表记录集
        :request: get
        :param: params dict 字典类型查询条件，目前只支持多个条件的“与”关系，不支持“或”、“非”关系
        :returns: json string
        """
        try:
            # token校验
            payload = APISecurity().verify_access_token()
            if not payload:
                return jsonify({'code': 901, 'msg': error_code[901]})

            odoo = odoorpc.ODOO(Config.ODOO_HOST, port=Config.ODOO_PORT)
            odoo.login(Config.ODOO_DB, payload['login'], payload['pwd'])
            domain = tools.dict_to_domain(request.json['params'])
            page = int(request.args['page']) if request.args.get('page', False) else 1
            pagesize = int(request.args['pagesize']) if request.args.get('pagesize', False) else 10
            offset = page * pagesize - pagesize
            if page == 1:
                total = odoo.env['{{ modelName }}'].search_count(domain)
            fields = odoo.env['{{ modelName }}'].get_fields_all()
            record_list = odoo.env['{{ modelName }}'].search_read(domain, fields, offset=offset, limit=pagesize, order='create_date desc')
            data_list = []
            for record in record_list:
                record = tools.dict_to_camel(record)
                data_list.append(record)
            if page == 1:
                data = {'total': total, 'list': data_list}
            else:
                data = {'list': data_list}
            return jsonify({'code': 0, 'msg': 'success', 'data': data})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 502, 'msg': error_code[502]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})
        finally:
            odoo.logout()
